<?php if ( ! defined('SERVER_ROOT')) exit('No direct script access allowed');
/**
 * MVC Ultra - A ultralight weight MVC framework for PHP
 *
 * MVC ultra is very simple MVC framework that is designed to be easy to use and learn.
 * It does not have all of other frameworks but you add what you need when you need it
 * and understand better whats going on.
 *
 *@author Warren Thomas <wiley_warren@yahoo.com>
 *@copyright Copyright (c) 2012.
 *
 ** 20121027/Warren Thomas      - Created MVC Ultra
 *
 */

/**
 * base view object for MVC Ultra
 *
 * @package core
 * 
 */
class ultra_view
{
    /**
     * Holds variables assigned to template
     */
    private $data = array();
    
    /**
     * hold available formats
     */
    private static $formats = array(
        'html' => array('','Content-Type: text/html; charset=utf-8'),
        'text' => array('.txt','Content-Type: text/plain'),
        'xml' => array('.xml','Content-Type:text/xml'),
    );

    /**
     * hold default format
     */
    private $format = null;
    
    private $template = null;
    
    public function __construct($template,$format='html')
    {
        $this->template = $template;
        $this->format = $format;
    }

    public function __set($variable , $value)
    {
        if($variable == 'format') $this->format = $value;
        $this->data[$variable] = $value;
    }
    
    public function __get($name){
        if($name == 'format') return $this->format;
        if(array_key_exists($name,$this->data)) return $this->data[$name];
        throw new UnexpectedValueException("No value '$name' set in ".__CLASS__);
    }
    
    /**
     *  Searches for formats from a parameter list
     */
    public static function getFormat(&$params){
        $format = FALSE;
        foreach(array_keys(self::$formats) as $type){
            $format = fetchParam($type,$params);
            if($format) return $format;
        }
        return $format;
    }
    
    public function __destruct(){
        //compose file name
        $file = VIEWS . '/' . strtolower($this->template) .self::$formats[$this->format][0]. '.php';
        if (file_exists($file)) {
            $response = $file;
        } else {
            $ex = new Exception("View file '$file' can't be found");
            render_error($ex);
        }
        //parse data variables into local variables, so that they render to the view
        $data = $this->data;
        // add start time to view
        $data['start_time'] = START_TIME;
        // set respose header for view
    
        if ( isset($this->format) ) {
            header(self::$formats[$this->format][1]);
            include($response);
        }
    }
} 